<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="时间选择" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="订单类型" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择订单类型" clearable size="small">
          <el-option label="正常" value="1" />
          <el-option label="限时抢购" value="2" />
          <el-option label="拼团" value="3" />
          <el-option label="兑换" value="4" />
        </el-select>
      </el-form-item>

      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" @change="handleQuery" clearable size="small">
          <el-option label="待支付" value="1" />
          <el-option label="已支付" value="2" />
          <el-option label="已关闭" value="3" />
          <el-option label="已发货" value="4" />
        </el-select>
      </el-form-item>

      <el-form-item label="订单编号" prop="orderNum">
        <el-input
          v-model="queryParams.orderNum"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="手机号" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入用户手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改
        </el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="订单编号" width="130" align="center" prop="orderNum" />
      <el-table-column label="时间" width="100" align="center" prop="createTime" />
      <el-table-column
        label="产品名称"
        width="160"
        align="center"
        prop="goodsName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="规格" align="center" prop="goodsStandard">
        <template slot-scope="scope">
          <span>{{scope.row.goodsStandard.desc}}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="50" align="center" prop="goodsNum" />
      <el-table-column label="金额" width="70" align="center" prop="orderMoney" />
      <el-table-column label="订单类型" width="80" align="center" prop="orderType">
        <template slot-scope="scope">
          <span>{{scope.row.orderType | filterOrderType}}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="80" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <span>{{scope.row.orderStatus | filterOrderStatus}}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户手机号" width="110" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.user">{{scope.row.user.phonenumber}}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户昵称" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.user">{{scope.row.user.nickName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户类别" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.user">{{scope.row.user.userType | filterUserType}}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" align="center">
        <template #default="{row}">
          <div>
            <div>
              {{row.orderAddress && row.orderAddress.split('#')[0]}}
            </div>
            <div>
              <span>{{row.orderAddress && row.orderAddress.split('#')[1]}} </span>
              <span style="margin-left: 2px">{{row.orderAddress && row.orderAddress.split('#')[2]}} </span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:order:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            class="delete-btn"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="deliver(scope.row)"
            v-hasPermi="['system:order:remove']"
            v-if="scope.row.orderStatus == 2"
          >发货</el-button>
          <el-button
            size="mini"
            type="text"
            @click="showWuliu(scope.row)"
            v-hasPermi="['system:order:query']"
            v-if="scope.row.orderStatus == 4"
          >物流信息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="订单名称" prop="orderName">
          <el-input v-model="form.orderName" placeholder="请输入订单名称" />
        </el-form-item>
        <el-form-item label="商品数量" prop="goodsNum">
          <el-input v-model="form.goodsNum" placeholder="请输入商品数量" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="form.orderType" placeholder="请选择订单类型">
            <el-option label="请选择字典生成" value />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-radio-group v-model="form.orderStatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="订单金额" prop="orderMoney">
          <el-input v-model="form.orderMoney" placeholder="请输入订单金额" />
        </el-form-item>
        <el-form-item label="下单用户" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入下单用户" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--发货对话框-->
    <el-dialog title="发货" :visible.sync="open1" width="650px" append-to-body @closed="wuliuClosed">
      <el-form ref="form" :model="shipment" label-width="80px">
        <el-form-item label="物流公司" prop="shipmentType">
          <el-select v-model="shipment.shipmentType" placeholder="请选择">
            <el-option :label="item.label" :value="item.key"
                       v-for="(item, index) in shipmentType">{{item.label}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="shipmentNumber">
          <el-input v-model="shipment.shipmentNumber" placeholder="请输入单号"/>
        </el-form-item>
        <el-form-item label="发货时间" prop="shipmentTime1" v-if="showWuliuflg">
          {{parseTime(shipment.shipmentTime1)}}
        </el-form-item>
        <el-timeline :reverse="true" v-if="wuliuData.length">
          <el-timeline-item
            v-for="(activity, index) in wuliuData"
            :key="index"
            :timestamp="activity.AcceptTime">
            {{activity.AcceptStation}}
          </el-timeline-item>
        </el-timeline>
        <div v-if="!wuliuData.length && showWuliuflg" style="text-align: center;padding-bottom: 30px">暂无物流信息</div>
        <div class="dialog-footer" style="text-align: center">
          <el-button type="primary" @click="deliverAction">确 定</el-button>
          <el-button @click="open1 = false">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  exportOrder,
  getShipTypeList,
  deliverAction,
  getShipmentListByNumber
} from "@/api/system/order";

export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      orderNums: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderType: null,
        userType: null,
        orderNum: null,
        phonenumber: null,
        nickName: null,
        startTime: null,
        endTime: null,
        time: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      open1: false,
      shipment:{},
      shipmentType: [],
      showWuliuflg: false,
      wuliuData: []
    };
  },
  filters: {
    filterOrderStatus(value) {
      return {
        1: "待支付",
        2: "已支付",
        3: "已关闭",
        4: "已发货",
        5: "交易成功"
      }[value];
    },
    filterOrderType(value) {
      return {
        1: "正常",
        2: "限时抢购",
        3: "拼团",
        4: "兑换"
      }[value];
    },
    filterUserType(value) {
      return {
        1: "普通用户",
        2: "推广员"
      }[value];
    }
  },
  created() {
    this.getList();
    getShipTypeList().then(res => {
      res.data.forEach(item => {
        var obj = {}
        for (let n in item) {
          obj['key'] = n
          obj['label'] = item[n]
        }
        this.shipmentType.push(obj)
      })
    })
  },
  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      const postData = this.queryParams.time
        ? {
            ...this.queryParams,
            startTime: this.filterDate(this.queryParams.time[0]),
            endTime: this.filterDate(this.queryParams.time[1])
          }
        : this.queryParams;
      delete postData.time;
      listOrder(postData).then(response => {
        this.orderList = response.rows.map(item => {
          item.goodsStandard = JSON.parse(item.goodsStandard);
          return item;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNum: null,
        orderName: null,
        goodsNum: null,
        goodsName: null,
        orderType: null,
        orderStatus: 0,
        orderMoney: null,
        userId: null,
        updateTime: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.orderNums = selection.map(item => item.orderNum);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    handleView(row) {
      this.$router.push({
        name: "OrderDetail",
        query: {
          id: row.id
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addOrder(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const orderNums = row.orderNum || this.orderNums;
      this.$confirm(
        '是否确认删除订单编号为"' + orderNums + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delOrder(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有订单数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportOrder(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function() {});
    },

    // 发货
    deliver(row) {
      this.open1 = true
      this.shipment = {}
      this.shipment.orderId = row.id
      this.showWuliuflg = false
    },

    deliverAction() {
      if (!this.shipment.shipmentType ) {
        this.$message({
          message: '请选择物流公司！',
          type: 'warning'
        });
        return
      }
      if (!this.shipment.shipmentNumber) {
        this.$message({
          message: '物流单号不能为空！',
          type: 'warning'
        });
        return
      }
      deliverAction(this.shipment).then(res => {
        this.$message({
          message: '发货成功！',
          type: 'success'
        });
        this.open1 = false
        this.getList()
      })
    },

    showWuliu(row) {
      getShipmentListByNumber({orderId: row.id}).then(res => {
        var data = JSON.parse(res.msg)
        this.showWuliuflg = true
        this.open1 = true
        this.shipment = {
          shipmentType: data.ShipperCode,
          shipmentNumber: data.LogisticCode,
          orderId: row.id,
          shipmentTime1: new Date(row.shipmentTime)
        }
        this.wuliuData = data.Traces
      })
    },

    wuliuClosed() {
      this.shipment = {}
      this.wuliuData = []
      this.showWuliuflg = false
    }
  }
};
</script>
